package de.tmahr.android;

import java.io.IOException;

import de.tmahr.android.logger.LogActivity;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class SoundPoolTest extends LogActivity implements OnTouchListener
{
	private SoundPool sp;
	int soundId = -1;

	public SoundPoolTest()
	{
		super(SoundPoolTest.class.getSimpleName());
	}

	@Override
	public void onCreate(Bundle b)
	{
		super.onCreate(b);
		textView.setOnTouchListener(this);

		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		
		final int nChannels = 15;
		log("Lege SoundPool mit " + nChannels + " Kanälen an");
		sp = new SoundPool(nChannels, AudioManager.STREAM_MUSIC, 0);

		try
		{
			AssetManager am = getAssets();
			AssetFileDescriptor desc = am.openFd("sound.wav");
			soundId = sp.load(desc, 1);
		}
		catch (IOException e)
		{
			log("Kann Klangdatei nicht laden: " + e.getMessage());
		}
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		if(isFinishing())
		{
			log("Gebe SoundPool frei");
			if(soundId!=-1)
			{
				sp.unload(soundId);
			}
			sp.release();
			sp = null;
		}
	}	

	@Override
	public boolean onTouch(View v, MotionEvent event)
	{
		if (event.getAction() == MotionEvent.ACTION_UP)
		{
			if (soundId != -1)
			{
				sp.play(soundId, 1, 1, 0, 0, 1);
			}
		}
		return true;
	}

}
